<?php
/**
 * 用户管理模块
 */

namespace app\controllers\marketing;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use app\components\TemplateMarket;
use app\models\marketing\MailTemplate;
use app\models\marketing\MailGroup;
use app\models\AutoMailTemplate;
use yii\data\Pagination;
use yii\helpers\Html;

class MailTemplateController extends \app\base\Controller
{
    public $enableCsrfValidation = false;
   
    /**
     * 模版类型添加
     */
    public function actionAddTemplateType()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        
        // 当前的系统，代表是营销邮件还是系统邮件
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        
        // 添加模版类型
        $TemplateMarket = new TemplateMarket();
        $returnData = $TemplateMarket->addTemplateType($formData);
        echo json_encode($returnData);
    }
    /**
     * 邮件模版列表
     */
    public function actionIndex()
    {
        Yii::$app->db->enableSlaves = false; //强制在主库上操作
        $data = [];
        $siteInfo = [];
        
        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        $siteInfo[0] = "全部";
        $authSiteIds = array();
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                $authSiteIds[] = $siteInfo_tmp_v['site_id'];
            }
        }
        
        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        
         // 站点id相关
        $formData['site_id'] = isset($formData['site_id']) ? $formData['site_id'] : 0;
        // 获取模版类型
        $TemplateMarket = new TemplateMarket();
        if (!empty($formData['site_id'])) {
            $templateTypeArr = $TemplateMarket->getTemplateType($formData['site_id']);
        } else {
            $templateTypeArr = $TemplateMarket->getTemplateType();
        }
        
        $templateTypeArrInfo = [];
        $templateTypeArrCompaign = [];
        $formData['tempType'] = [];
        //$formData['temp_type_id'] = 0;
        $templateTypeArrInfo[0] = "全部";
        if (isset($templateTypeArr) && is_array($templateTypeArr)) {
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                $templateTypeArrInfo[$templateTypeArrV['id']] = $templateTypeArrV['template_type_name'];
               
            } 
            //$formData['temp_type_id'] = $templateTypeArr[0]['id'];
            $formData['tempType'] = $templateTypeArrInfo;
        }
        $formData['siteInfo'] = $siteInfo;
        $sessionAllowWeb  = Yii::$app->session['admin_info']['allow_web'];
       
        $formData['temp_type_id'] = isset($formData['temp_type_id']) ? intval($formData['temp_type_id']) : 0;
        $formData['type_id'] = $formData['temp_type_id'];
        
        $formData['site_ids'] = $sessionAllowWeb == 'all' ? 0 : $authSiteIds;
       
        $formData['email_type_condition'] = isset($formData['email_type_condition']) ? intval($formData['email_type_condition']) : 1;
        $formData['keyword'] = isset($formData['keyword']) ? trim(addslashes($formData['keyword'])) : "";
        
        // 分页参数相关
        $page = Yii::$app->request->$mothod('page') ? Yii::$app->request->$mothod('page') : 1;
        $pageSize = Yii::$app->request->$mothod('pagesize') ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
        
        $formData['page'] = $page;
        $formData['pageSize'] = $pageSize;
        
        // 获取邮件模版数据
        $TemplateMarket = new TemplateMarket();
        
        
        $dataSelect = $TemplateMarket->getTemplate($formData);
        
        $totalCount = $dataSelect['totalCount'];
        // 分页相关
        $pages = new Pagination(['totalCount' =>$totalCount, 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
        return $this->render('//marketing//mail-template/list',[
            'data' => $dataSelect['temp_info'],
            'formData' => $formData,
            'site' => $site,
            'pages' => $pages,
        ]);
    }
    
    /*
     * 发送内测邮件
     */
    public function actionSendInnerTest()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $get_site_id = Yii::$app->request->$mothod('site_id');
        $site = Yii::$app->request->$mothod('site');
        $type = Yii::$app->request->$mothod('type');
        $id = Yii::$app->request->$mothod('id');
        $data = [];
        if($type == 'ab_test') {
            $groupModel = new MailGroup();
            if($data = $groupModel->getAbTestChildMailGroupById($id)) {
                $site_id = $data['site_id'];
                $template_id = $data['template_id'];
            }
        } else {
            $template_id = Yii::$app->request->$mothod('template_id');
            $site_id = intval($get_site_id);
        }
        if(!$site_id)
        {
            $this->sysMsg('警告', '网站ID不存在!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        $siteInfo = [];
        // 当前用户所有有权限的站点
        $siteInfoTmp = Yii::$app->authority->getMarketEmailAccessSite();
        if (isset($siteInfoTmp) && is_array($siteInfoTmp)) {
            foreach ($siteInfoTmp as $siteInfoTmpK => $siteInfoTmpV) {
                $siteInfo[$siteInfoTmpV['site_id']] = $siteInfoTmpV['name'];
            }
        }
        
        $insideTestUsers = Yii::$app->usermanagemarket->getInsideTestBySiteid($site_id);
        
        return $this->render('//marketing//mail-template/send-inner-test',[
            'data' => $insideTestUsers,
            'site_id' => $site_id,
            'type' => $type,
            'ab_test_data' => $data,
            'site'    => $site,
            'template_id'  => $template_id,
            'siteInfo' => $siteInfo
        ]);
    }
    
    /**
     * 编辑提交相关
     */
    public function actionDoEdit()
    {
        $data = [];
        $siteInfo = [];
        
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
       
        
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : 0;
        
        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                 $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        } else {
            $this->sysMsg('警告', '必须选择邮件模版所属网站!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
    
        // 添加模版
        $TemplateMarket = new TemplateMarket();
        $returnData = $TemplateMarket->editTemplate($formData);
        
        $rtnUrl = "/marketing/mail-template/index?site=marketing_email";
        // 数据添加成功则跳转到列表页面失败则跳转回上一页
        if ($returnData['status'] != 0) {
             $this->sysMsg('警告', $returnData['errorInfo'],$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        } else {
            $this->sysMsg('提示', $returnData['errorInfo'],$params = [ 'type' => 'success', 'links' => [ ['name'=>'返回上一页' , 'url'=>$rtnUrl] ] ]);
        }
    }
    
    /**
     * 编辑提交相关ajax版
     */
    public function actionDoEditAjax()
    {
        $data = [];
        $siteInfo = [];
        
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
       
        
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : 0;
        
        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                $returnData['status'] = 100;
                $returnData['errorInfo'] = "你的账号该没有权限!";
                echo json_encode($returnData);
                exit;
            }
        } else {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "请选择网站";
            echo json_encode($returnData);
            exit;
        }
    
        // 添加模版
        $TemplateMarket = new TemplateMarket();
        $returnData = $TemplateMarket->editTemplate($formData);
        
        echo json_encode($returnData);
        exit;
    }
    /**
     * 邮件模版添加确认ajax版
     */
    public function actionDoAddAjax()
    {
        $data = [];
        $siteInfo = [];
        
        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : 0;

        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                $returnData['status'] = 100;
                $returnData['errorInfo'] = "你的账号该没有权限!";
                echo json_encode($returnData);
                exit;
            }
        } else {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "请选择网站";
            echo json_encode($returnData);
            exit;
        }
        
       
        // 添加模版
        $TemplateMarket = new TemplateMarket();
        $returnData = $TemplateMarket->addTemplate($formData);
        
        echo json_encode($returnData);
        exit;
        
    }
    /**
     * 邮件模版添加确认
     */
    public function actionDoAdd()
    {
        $data = [];
        $siteInfo = [];
        
        $defaultPageSize = 20;
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
         // 查询网站相关的数据
        $formData = Yii::$app->request->$mothod();
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? intval($formData['site_id']) : 0;
        
        if ($formData['site_id']) {
            $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
            if (!$flag) {
                 $this->sysMsg('警告', '你的账号没有权限!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            }
        } else {
            $this->sysMsg('警告', '必须选择邮件模版所属网站!',$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        }
        
        
        // 添加模版
        $TemplateMarket = new TemplateMarket();
        $returnData = $TemplateMarket->addTemplate($formData);
        
        $rtnUrl = "/marketing/mail-template/index?site=marketing_email";
        // 数据添加成功则跳转到列表页面失败则跳转回上一页
        if ($returnData['status'] != 0) {
             
             $this->sysMsg('警告', $returnData['errorInfo'],$params = [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
        } else {
            $this->sysMsg('提示', $returnData['errorInfo'],$params = [ 'type' => 'success', 'links' => [ ['name'=>'返回上一页' , 'url'=>$rtnUrl] ] ]);
        }
        
        
    }
    /**
     * 邮件模版添加
     */
    public function actionAdd()
    {
        
        $data = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
       
        // 当前用户所有有权限的站点
        $siteInfo_tmp = Yii::$app->authority->getMarketEmailAccessSite();
        
        if (isset($siteInfo_tmp) && is_array($siteInfo_tmp)) {
            foreach ($siteInfo_tmp as $siteInfo_tmp_k => $siteInfo_tmp_v) {
                $siteInfo[$siteInfo_tmp_v['site_id']] = $siteInfo_tmp_v['name'];
                $siteCode[$siteInfo_tmp_v['site_id']] = Yii::$app->params['sites']['marketing_email']['web_config'][$siteInfo_tmp_v['name']]['brief_code'];
            }
        }
       
        if (empty($siteInfo)) {
            exit('你好，你没有任何网站的相关权限');
        }
        $formData['siteInfo'] = $siteInfo;
        $formData['siteCode'] = $siteCode;
        // 当前搜索哪个网站的用户信息
        $formData['site_id'] = isset($formData['site_id']) ? (int)$formData['site_id'] : array_keys($siteInfo)[0];
       
        // 获取当前站点下所有的自定义模板
        $autoMailModel = new AutoMailTemplate;
        $allAutoTemplates = $autoMailModel->getAutoMailTemplateBySiteId($formData['site_id']);
        $autoTemplate = [];
        foreach($allAutoTemplates as $allAutoTemplate) {
            $autoTemplate[$allAutoTemplate['id']] = $allAutoTemplate['template_name'];
        }
        
        // 获取模版类型
        $TemplateMarket = new TemplateMarket();
        $templateTypeArr = $TemplateMarket->getTemplateType($formData['site_id']);
        $templateTypeArrInfo = [];
        $templateTypeArrInfo[0] = '--选择类型--';
        $templateTypeArrCompaign = [];
        $templateTypeArrCompaign[0] = '--选择类型--';
        $templateTypeArrTrigger = [];
        $templateTypeArrTrigger[0] = 1;
        $templateTypeArrTriggerReal = [];
        $templateTypeArrTriggerReal[0] = 1;
        
        $formData['tempType'] = [];
        $formData['temp_type_id'] = !empty($formData['temp_type_id']) ? $formData['temp_type_id'] : 0;
        $formData['tempTypeCompaign'] = [];
        $formData['tempTypeTrigger'] = [];
        $formData['tempTypeTriggerReal'] = [];
        $activeTemplateNum = [];
        $activeTemplateNumDeal = [];
        $selfMotionArr = [];
        $selfMotionStr = "";
        if (isset($templateTypeArr) && is_array($templateTypeArr)) {
            $templateTypeIdArr = [];
            $templateTypeIdStr = '';
            
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                if ($templateTypeArrV['trigger_type'] == 0) { // 说明是自动触发的相关邮件
                    $templateTypeIdArr[] = $templateTypeArrV['id'];
                } 
            }
          
            $templateTypeIdStr = join(',',$templateTypeIdArr);
            if ($templateTypeIdStr) { // 获取每个模版类型下是否有启用的模版
                $activeTemplateNum = $TemplateMarket->getUsedTemplateNumByTypeId($templateTypeIdStr);
                foreach ($activeTemplateNum as $activeTemplateNumK => $activeTemplateNumV) {
                    $activeTemplateNumDeal[$activeTemplateNumV['type_id']] = $activeTemplateNumV;
                }
            }
           
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                $templateTypeArrInfo[$templateTypeArrV['id']] = $templateTypeArrV['template_type_name'];
                $templateTypeArrCompaign[$templateTypeArrV['id']] = $templateTypeArrV['template_type_compaign'];
                if ($templateTypeArrV['trigger_type'] == 0 && isset($activeTemplateNumDeal[$templateTypeArrV['id']]) && $activeTemplateNumDeal[$templateTypeArrV['id']] > 0 ) { // 如果是自动发送的邮件模版类型，并且当前模版类型有启用的模版
                    $templateTypeArrTrigger[$templateTypeArrV['id']] = 0;
                } else {
                    $templateTypeArrTrigger[$templateTypeArrV['id']] = 1; 
                }
                
                if ($templateTypeArrV['trigger_type'] == 0) {
                    $selfMotionArr[] = $templateTypeArrV['id'];
                    $templateTypeArrTriggerReal[$templateTypeArrV['id']] = 0;
                } else {
                    $templateTypeArrTriggerReal[$templateTypeArrV['id']] = 1;
                }
            } 
            $formData['temp_type_id'] = !empty($formData['temp_type_id']) ? $formData['temp_type_id'] : 0;
            $formData['tempType'] = $templateTypeArrInfo;
            $formData['tempTypeCompaign'] = $templateTypeArrCompaign;
            $formData['tempTypeTrigger'] = $templateTypeArrTrigger;
            $formData['tempTypeTriggerReal'] = $templateTypeArrTriggerReal;
            $selfMotionStr = join(',' , $selfMotionArr);
           
        }

        //$session        = Yii::$app->session;
        //$admin_info     = $session['admin_info'];
        //echo '<pre>';
       // var_dump($admin_info);
       // exit;
        return $this->render('//marketing//mail-template/add',[
            'data' => $data, 
            'formData' => $formData,
            'autoTemplate'    => $autoTemplate,
            'selfMotionStr' => $selfMotionStr,
            'site' => $site,
        ]);
    }
    /*
     * 根据条件获取模板类型
     */
    public function actionGetTemplateType()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $site_id = Yii::$app->request->$mothod('site_id');

         // 获取模版类型
        $TemplateMarket = new TemplateMarket();
        $templateTypeArr = $TemplateMarket->getTemplateType($site_id);
        $templateTypeArrInfo = [];
        $templateTypeArrInfo[0] = '--选择类型--';
        $templateTypeArrCompaign = [];
        $templateTypeArrCompaign[0] = '--选择类型--';
        $templateTypeArrTrigger = [];
        $templateTypeArrTrigger[0] = 1;
        $templateTypeArrTriggerReal = [];
        $templateTypeArrTriggerReal[0] = 1;
        
        $formData['tempType'] = [];
        $formData['temp_type_id'] = 0;
        $formData['tempTypeCompaign'] = [];
        $formData['tempTypeTrigger'] = [];
        $formData['tempTypeTriggerReal'] = [];
        $activeTemplateNum = [];
        $activeTemplateNumDeal = [];
        $selfMotionArr = [];
        $selfMotionStr = "";
        if (isset($templateTypeArr) && is_array($templateTypeArr)) {
            $templateTypeIdArr = [];
            $templateTypeIdStr = '';
            
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                if ($templateTypeArrV['trigger_type'] == 0) { // 说明是自动触发的相关邮件
                    $templateTypeIdArr[] = $templateTypeArrV['id'];
                } 
            }
          
            $templateTypeIdStr = join(',',$templateTypeIdArr);
            if ($templateTypeIdStr) { // 获取每个模版类型下是否有启用的模版
                $activeTemplateNum = $TemplateMarket->getUsedTemplateNumByTypeId($templateTypeIdStr);
                foreach ($activeTemplateNum as $activeTemplateNumK => $activeTemplateNumV) {
                    $activeTemplateNumDeal[$activeTemplateNumV['type_id']] = $activeTemplateNumV;
                }
            }
            
            foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                $templateTypeArrInfo[$templateTypeArrV['id']] = $templateTypeArrV['template_type_name'];
                $templateTypeArrCompaign[$templateTypeArrV['id']] = $templateTypeArrV['template_type_compaign'];
                
                if ($templateTypeArrV['trigger_type'] == 0 && isset($activeTemplateNumDeal[$templateTypeArrV['id']]) && $activeTemplateNumDeal[$templateTypeArrV['id']] > 0 ) { // 如果是自动发送的邮件模版类型，并且当前模版类型有启用的模版
                    $templateTypeArrTrigger[$templateTypeArrV['id']] = 0;
                } else {
                    $templateTypeArrTrigger[$templateTypeArrV['id']] = 1; 
                }
                
                if ($templateTypeArrV['trigger_type'] == 0) {
                    $selfMotionArr[] = $templateTypeArrV['id'];
                    $templateTypeArrTriggerReal[$templateTypeArrV['id']] = 0;
                } else {
                    $templateTypeArrTriggerReal[$templateTypeArrV['id']] = 1;
                } 
            } 
            
            $formData['temp_type_id'] = "0";
            $formData['tempType'] = Html::dropDownList('temp_type_id',$formData['temp_type_id'],$templateTypeArrInfo, ['class' => 'form-control z-select mr10 mb5']);
            $formData['tempTypeCompaign'] = Html::dropDownList('temp_type_compaign',$formData['temp_type_id'],$templateTypeArrCompaign, ['class' => 'form-control z-select mr10 mb5']);
            $formData['tempTypeTrigger'] = Html::dropDownList('temp_type_trigger',$formData['temp_type_id'],$templateTypeArrTrigger, ['class' => 'form-control z-select mr10 mb5']);
            $formData['tempTypeTriggerReal'] = Html::dropDownList('temp_type_trigger_real',$formData['temp_type_id'],$templateTypeArrTriggerReal, ['class' => 'form-control z-select mr10 mb5']);
            $selfMotionStr = join(',' , $selfMotionArr);
            $formData['selfMotionStr'] = $selfMotionStr;
            
            
        }
        $return = array(
            'status'  => 1,
            'datas'    => $formData
        );
        echo json_encode($return);exit;
    }
    /*
     * 首页根据条件获取模板类型
     */
    public function actionGetIndexTemplateType()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $site_id = Yii::$app->request->$mothod('site_id');
        $mail_business = Yii::$app->request->$mothod('mail_business');
        
        $templateTypeArrInfo = [];
        if($mail_business == 1) { 
        
            $templateTypeArrInfo[0] = '全部';
        } else {
            // 获取模版类型
            $TemplateMarket = new TemplateMarket();
            $templateTypeArr = $TemplateMarket->getTemplateType($site_id);
            if (isset($templateTypeArr) && is_array($templateTypeArr)) {

                foreach ($templateTypeArr as $templateTypeArrK => $templateTypeArrV) {
                    $templateTypeArrInfo[$templateTypeArrV['id']] = $templateTypeArrV['template_type_name'];

                } 

            }
        }
        $formData['tempType'] = [];
        $formData['temp_type_id'] = "0";
        $formData['tempType'] = Html::dropDownList('temp_type_id',$formData['temp_type_id'],$templateTypeArrInfo, ['class' => 'form-control z-select mr10 mb5']);
        $return = array(
            'status'  => 1,
            'datas'    => $formData
        );
        echo json_encode($return);exit;
    }
    
    /*
     * 异步获取注册来源
     */
    public function actionGetRegSource()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $site_id = Yii::$app->request->$mothod('site_id');
        $mail_business = Yii::$app->request->$mothod('mail_business');

         // 获取模版类型
        if($site_id == 12 && $mail_business == 1) {
            $reg_source = TemplateMarket::regSourceList($site_id);
        } else {
            $reg_source = ['ALL' => '全站'];
        }
        
        
        $formData['regSource'] = Html::dropDownList('reg_source','ALL',$reg_source, ['class' => 'form-control js-select2-search mr10 mb5']);
        
        $return = array(
            'status'  => 1,
            'datas'    => $formData
        );
        echo json_encode($return);exit;
    }
    
    /**
     * 邮件模版编辑
     */
    public function actionEdit()
    {
        Yii::$app->db->enableSlaves = false; // 强制在主库上操作
        $data = [];
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();
        
        // 获取当前模版的相关数据
        $TemplateMarket = new TemplateMarket();
        
        $data =  $TemplateMarket->getTemplateOne($formData);
        
        // 处理相关数据
        $data['site_name'] =  isset(Yii::$app->params['sites']['marketing_email']['web_index'][$data['site_id']]) ? Yii::$app->params['sites']['marketing_email']['web_index'][$data['site_id']] : "";
        
        $data['brief_code'] = isset(Yii::$app->params['sites']['marketing_email']['web_config'][$data['site_name']]['brief_code']) ? Yii::$app->params['sites']['marketing_email']['web_config'][$data['site_name']]['brief_code'] : "";
        
        $data['template_name'] = stripslashes($data['template_name']);
        $data['template_subject'] = stripslashes($data['template_subject']);
        $data['template_content'] = stripslashes($data['template_content']);
        $data['custom_track_code'] = stripslashes($data['custom_track_code']);
       
        // 如果当前模版为禁用状态，并且当前邮件模版类型为自动发送状态。则查询当前站点是否相同类型的并且是启用状态的模版
        $data['is_not_have_active_template'] = 1; 
        if ($data['trigger_type'] == 0 && $data['status'] == 0) {
            
            // 查询到
            $activeTemplateNum = $TemplateMarket->getUsedTemplateNumByTypeId($data['type_id']);
            if (isset($activeTemplateNum[0]) && $activeTemplateNum[0]['tempCount'] > 0) {
                 $data['is_not_have_active_template'] = 0;
            }
        }
        
        return $this->render('//marketing//mail-template/edit',[
            'data' => $data, 
           
            'site' => $site,
        ]);
    }
    
    /**
     * 邮件模版删除
     */
    public function actionDelete()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $formData = Yii::$app->request->$mothod();
        
        // 删除相关
        $TemplateMarket = new TemplateMarket();
        $returnData = $TemplateMarket->doDelete($formData);
        echo json_encode($returnData);
        exit;
    }

    /**
     * 获取模板
     */
    public function actionGetTemplateBySiteId()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method('siteId');

        if (empty($siteId)) {
            $this->returnJson(10001, "数据不完整，请提交网站名称");
        }

        $templateModel = new MailTemplate();
        $data = $templateModel->getTemplate(["site_id" => $siteId, "is_del" => 0]);
        $this->returnJson(0, "success", $data);
    }
    /**
     * 获取模板
     */
    public function actionGetTemplateByTemplateName()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method('siteId');
        $templateName= yii::$app->request->$method('template_name');
        $templateName = !empty($templateName) ? addslashes(trim($templateName)):"";
        if (empty($siteId)) {
            $this->returnJson(10001, "数据不完整，请提交网站名称");
        }

        // 当前网站有没有相同名字的邮件模版
        $tempSql = "select id from mail_template where site_id = {$siteId} and template_name = '{$templateName}' and is_del = 0";
        if(Yii::$app->db->createCommand($tempSql)->queryOne()) {
            $data['is_exsit'] = 1;
        } else {
            $data['is_exsit'] = 0;
        }
        $this->returnJson(0, "success", $data);
    }
    /*
     * 获取指定网站，模板类型的模板数据
     */
    public function actionGetTemplateByTypeId()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method('site_id');
        $templateId = yii::$app->request->$method('template_id');

        if (empty($siteId) || empty($templateId)) {
            $this->returnJson(10001, "数据不完整");
        }

        $templateModel = new MailTemplate();
        $data = $templateModel->getTemplate(["site_id" => $siteId, 'template_id' => $templateId, "is_del" => 0, "is_use" => 1, 'status' => 1, 'is_ab_test' => 0]);
        
        $data = array_shift($data);
        if($data) {
            $data['template_subject'] = stripcslashes($data['template_subject']);
            $data['template_content'] = stripcslashes($data['template_content']);
        }
        $this->returnJson(0, "success", $data);
        
    }
    
    /*
     * 获取指定网站，模板类型的模板数据
     */
    public function actionGetTestTemplateById()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method('site_id');
        $id = yii::$app->request->$method('id');

        if (empty($siteId) || empty($id)) {
            $this->returnJson(10001, "数据不完整");
        }
        
        $templateModel = new MailTemplate();
        $groupModel = new MailGroup();
        
        $data = $groupModel->getAbTestChildMailGroupById($id);
        $templateData = $templateModel->getAbTestTemplateDetailById($siteId, $data['template_id']);
        
        $templateData = array_shift($templateData);
        if($templateData) {
            $templateData['template_subject'] = stripcslashes($templateData['template_subject']);
            $templateData['template_content'] = stripcslashes($templateData['template_content']);
        }
        $this->returnJson(0, "success", $templateData);
        
    }
   
} 